package com.cbn.ibcp.web.init;

import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.dynamic.datasource.DynamicRoutingDataSource;
import com.baomidou.dynamic.datasource.creator.DefaultDataSourceCreator;
import com.baomidou.dynamic.datasource.spring.boot.autoconfigure.DataSourceProperty;
import com.cbn.ibcp.common.utils.bean.BeanUtils;
import com.cbn.ibcp.jishiting.rms.domain.OrgDataSource;
import com.cbn.ibcp.jishiting.rms.service.IOrgDataSourceService;
import lombok.RequiredArgsConstructor;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;

import javax.sql.DataSource;
import java.util.List;

@RequiredArgsConstructor
@Component
public class LoadDatasource implements CommandLineRunner {

    private final IOrgDataSourceService orgDataSourceService;

    private final DataSource dataSource;

    private final DefaultDataSourceCreator defaultDataSourceCreator;

    public static List<String> notInjectOrgCodeList = CollectionUtil.toList("BJGH_cdd", "bjyst_cdd", "CQSW_cdd", "FJSW_cdd", "GSSW_cdd", "GUANGZHOU_cdd", "HeNanGD_kd", "HUBSW_cdd", "SXSSW_cdd", "TJSW_cdd", "QAonly_kd");

    @Override
    public void run(String... args) throws Exception {

        List<OrgDataSource> orgDataSourceList = orgDataSourceService.getList();
        for (OrgDataSource orgDataSource : orgDataSourceList) {
            if (notInjectOrgCodeList.contains(orgDataSource.getCode())) {
                continue;
            }
            DataSourceProperty dataSourceProperty = new DataSourceProperty();
            BeanUtils.copyProperties(orgDataSource, dataSourceProperty);
            String url = dataSourceProperty.getUrl();
            url = url.replace("mctjsvur9rl91pe1z7ah-rw4rm.maxscale.rds.ops.cbncloud.com", "10.8.9.64");
            dataSourceProperty.setUrl(url);
            dataSourceProperty.setUsername("office_readonly");
            dataSourceProperty.setPassword("6ifsXOjG72024");
            DynamicRoutingDataSource source = (DynamicRoutingDataSource) dataSource;
            DataSource dataSource = defaultDataSourceCreator.createDataSource(dataSourceProperty);
            source.addDataSource(orgDataSource.getCode(), dataSource);
        }
    }
}
